package com.wanghai.carwashing.api.exception;

import com.wanghai.carwashing.common.helper.JsonHelper;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/**
 * 全局异常处理
 * <p/>
 * 处理我们定义的ApiException和其他所有Exception
 * <p/>
 * 封装成json的形式进行response
 * @author 王海
 */
@ControllerAdvice
public class GenericExceptionHandler extends  ResponseEntityExceptionHandler{
   
    @ExceptionHandler({ApiException.class})
    public ResponseEntity<Object> handleApiException(ApiException ex,WebRequest webRequest){
        Map<String,Object> map = new LinkedHashMap<String,Object>();
        map.put("success",false);
        map.put("code", ex.getCode());
        map.put("message", ex.getDesc());
        map.put("requestUri",getRequestUri(webRequest));
        map.put("method", getRequestMethod(webRequest));
        map.put("params", webRequest.getParameterMap());
        final String json = JsonHelper.buildJsonString(map);
        HttpStatus status = HttpStatus.valueOf(ex.getStatusCode());
        return handleExceptionInternal(ex, json, JsonHelper.buildJsonHeaders(), status, webRequest);
    }
    
       // help function
    private String getRequestUri(WebRequest webRequest) {
        final String desc = webRequest.getDescription(false);
        final String uri = desc.substring(desc.indexOf('=') + 1);
        return uri;
    }

    private String getRequestMethod(WebRequest webRequest) {
        final String method;
        if (webRequest instanceof ServletWebRequest) {
            method = ((ServletWebRequest) webRequest).getRequest().getMethod();
        } else {
            method = "";
        }
        return method;
    }
}
